#!/usr/bin/env python3

import os
import re
import sys
import getpass
from http.cookiejar import MozillaCookieJar
import logging

import requests

from nicelogger import enable_pretty_logging

cookiefile = os.path.expanduser('~/scripts/python/pydata/aur.cookie')
token_pattern = re.compile(r'[a-f0-9]{32}')

def main(files):
  s = requests.Session()
  s.cookies = MozillaCookieJar(cookiefile)
  if os.path.exists(cookiefile):
    s.cookies.load()
  try:
    for f in files:
      upload(s, f)
  finally:
    s.cookies.save()

def login(s):
  duser = os.environ.get('USER', '')
  if duser:
    user = input('User (default %s): ' % duser) or duser
  else:
    user = input('User: ')
  password = getpass.getpass()
  r = s.post('https://aur.archlinux.org/login', {
    'user': user,
    'passwd': password,
    'remember_me': 'on',
  }, allow_redirects=False)
  if r.status_code != 302:
    print('Login failed.')
    return False
  else:
    return True

def upload(s, f):
  while True:
    d = s.get('https://aur.archlinux.org/pkgsubmit.php').text
    if d.find('You must create an account') != -1:
      while not login(s):
        pass
    else:
      token = token_pattern.findall(d)[0]
      break

  postdata = {
    'category': '1',
    'pkgsubmit': '1',
    'token': token,
  }
  s.post('https://aur.archlinux.org/submit/', postdata,
         files = {'pfile': open(f, 'rb')},
         allow_redirects = False)

if __name__ == '__main__':
  enable_pretty_logging(logging.DEBUG)
  main(sys.argv[1:])
